
const { Op } = require('sequelize');
const { Order, OrderItem, Product, Cart, User } = require('../models');

// 创建订单
exports.createOrder = async (req, res, next) => {
  const transaction = await sequelize.transaction();

  try {
    const userId = req.user.id;
    const { shippingAddress, billingAddress, paymentMethod, notes } = req.body;

    // 获取购物车商品
    const cartItems = await Cart.findAll({
      where: { userId },
      include: [
        {
          model: Product,
          as: 'product',
          attributes: ['id', 'name', 'sku', 'images', 'price', 'stock', 'isActive']
        }
      ],
      transaction
    });

    if (cartItems.length === 0) {
      await transaction.rollback();
      return res.status(400).json({
        success: false,
        message: '购物车为空'
      });
    }

    // 验证商品状态和库存
    let subtotal = 0;
    const orderItems = [];

    for (const cartItem of cartItems) {
      const product = cartItem.product;

      if (!product || !product.isActive) {
        await transaction.rollback();
        return res.status(400).json({
          success: false,
          message: `商品 ${product ? product.name : '未知'} 已下架`
        });
      }

      if (product.stock < cartItem.quantity) {
        await transaction.rollback();
        return res.status(400).json({
          success: false,
          message: `商品 ${product.name} 库存不足,当前库存:${product.stock}`
        });
      }

      const itemTotal = parseFloat(product.price) * cartItem.quantity;
      subtotal += itemTotal;

      orderItems.push({
        productId: product.id,
        productName: product.name,
        productSku: product.sku,
        productImage: product.images && product.images.length > 0 ? product.images[0] : null,
        quantity: cartItem.quantity,
        unitPrice: product.price,
        totalPrice: itemTotal.toFixed(2)
      });
    }

    // 计算费用
    const taxRate = 0.08; // 8% 税率
    const taxAmount = subtotal * taxRate;
    const shippingAmount = subtotal > 100 ? 0 : 10; // 满100免运费
    const totalAmount = subtotal + taxAmount + shippingAmount;

    // 创建订单
    const order = await Order.create({
      orderNumber: Order.generateOrderNumber(),
      userId,
      status: 'pending',
      subtotal: subtotal.toFixed(2),
      taxAmount: taxAmount.toFixed(2),
      shippingAmount: shippingAmount.toFixed(2),
      totalAmount: totalAmount.toFixed(2),
      paymentMethod,
      shippingAddress,
      billingAddress: billingAddress || shippingAddress,
      notes
    }, { transaction });

    // 创建订单项
    await OrderItem.bulkCreate(
      orderItems.map(item => ({ ...item, orderId: order.id })),
      { transaction }
    );

    // 更新商品库存和销售数量
    for (const cartItem of cartItems) {
      await Product.decrement('stock', {
        by: cartItem.quantity,
        where: { id: cartItem.productId },
        transaction
      });

      await Product.increment('salesCount', {
        by: cartItem.quantity,
        where: { id: cartItem.productId },
        transaction
      });
    }

    // 清空购物车
    await Cart.destroy({
      where: { userId },
      transaction
    });

    await transaction.commit();

    // 获取完整订单信息
    const fullOrder = await Order.findByPk(order.id, {
      include: [
        {
          model: OrderItem,
          as: 'orderItems'
        }
      ]
    });

    res.status(201).json({
      success: true,
      message: '订单创建成功',
      data: { order: fullOrder }
    });
  } catch (error) {
    await transaction.rollback();
    next(error);
  }
};

// 获取用户订单列表
exports.getUserOrders = async (req, res, next) => {
  try {
    const userId = req.user.id;
    const { page = 1, limit = 10, status } = req.query;
    const offset = (page - 1) * limit;
    const whereClause = { userId };

    if (status) {
      whereClause.status = status;
    }

    const { count, rows: orders } = await Order.findAndCountAll({
      where: whereClause,
      include: [
        {
          model: OrderItem,
          as: 'orderItems',
          attributes: ['id', 'productName', 'productImage', 'quantity', 'unitPrice', 'totalPrice']
        }
      ],
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']]
    });

    res.json({
      success: true,
      data: {
        orders,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total: count,
          pages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    next(error);
  }
};

// 获取订单详情
exports.getOrder = async (req, res, next) => {
  try {
    const userId = req.user.id;
    const { id } = req.params;

    const order = await Order.findOne({
      where: { id, userId },
      include: [
        {
          model: OrderItem,
          as: 'orderItems',
          include: [
            {
              model: Product,
              as: 'product',
              attributes: ['id', 'name', 'images', 'isActive']
            }
          ]
        }
      ]
    });

    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    res.json({
      success: true,
      data: { order }
    });
  } catch (error) {
    next(error);
  }
};

// 取消订单
exports.cancelOrder = async (req, res, next) => {
  const transaction = await sequelize.transaction();

  try {
    const userId = req.user.id;
    const { id } = req.params;

    const order = await Order.findOne({
      where: { id, userId },
      include: [
        {
          model: OrderItem,
          as: 'orderItems'
        }
      ],
      transaction
    });

    if (!order) {
      await transaction.rollback();
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    if (!order.canBeCancelled()) {
      await transaction.rollback();
      return res.status(400).json({
        success: false,
        message: '订单当前状态不允许取消'
      });
    }

    // 恢复库存和销售数量
    for (const item of order.orderItems) {
      await Product.increment('stock', {
        by: item.quantity,
        where: { id: item.productId },
        transaction
      });

      await Product.decrement('salesCount', {
        by: item.quantity,
        where: { id: item.productId },
        transaction
      });
    }

    // 更新订单状态
    await order.update({ status: 'cancelled', paymentStatus: 'refunded' }, { transaction });

    await transaction.commit();

    res.json({
      success: true,
      message: '订单已取消',
      data: { order }
    });
  } catch (error) {
    await transaction.rollback();
    next(error);
  }
};

// 模拟支付
exports.processPayment = async (req, res, next) => {
  const transaction = await sequelize.transaction();

  try {
    const userId = req.user.id;
    const { id } = req.params;
    const { paymentMethod } = req.body;

    const order = await Order.findOne({
      where: { id, userId, status: 'pending' },
      transaction
    });

    if (!order) {
      await transaction.rollback();
      return res.status(404).json({
        success: false,
        message: '订单不存在或状态不正确'
      });
    }

    // 模拟支付处理(90% 成功率)
    const paymentSuccess = Math.random() > 0.1;

    if (paymentSuccess) {
      await order.update({
        status: 'paid',
        paymentStatus: 'completed',
        paymentMethod,
        paidAt: new Date()
      }, { transaction });

      await transaction.commit();
      return res.json({
        success: true,
        message: '支付成功',
        data: { order }
      });
    } else {
      await order.update({
        paymentStatus: 'failed'
      }, { transaction });

      await transaction.commit();
      return res.status(400).json({
        success: false,
        message: '支付失败,请重试'
      });
    }
  } catch (error) {
    await transaction.rollback();
    next(error);
  }
};

// 管理员:获取所有订单
exports.getAllOrders = async (req, res, next) => {
  try {
    const { page = 1, limit = 20, status, userId, startDate, endDate } = req.query;
    const offset = (page - 1) * limit;
    const whereClause = {};

    if (status) whereClause.status = status;
    if (userId) whereClause.userId = userId;
    if (startDate || endDate) {
      whereClause.createdAt = {};
      if (startDate) whereClause.createdAt[Op.gte] = new Date(startDate);
      if (endDate) whereClause.createdAt[Op.lte] = new Date(endDate);
    }

    const { count, rows: orders } = await Order.findAndCountAll({
      where: whereClause,
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'email', 'firstName', 'lastName']
        },
        {
          model: OrderItem,
          as: 'orderItems',
          attributes: ['id', 'productName', 'quantity', 'unitPrice', 'totalPrice']
        }
      ],
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']]
    });

    res.json({
      success: true,
      data: {
        orders,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total: count,
          pages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    next(error);
  }
};

// 管理员:更新订单状态
exports.updateOrderStatus = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { status, trackingNumber } = req.body;

    const order = await Order.findByPk(id);
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    const updateData = { status };
    // 发货状态处理
    if (status === 'shipped') {
      updateData.trackingNumber = trackingNumber;
      updateData.shippedAt = new Date();
    }
    // 送达状态处理
    if (status === 'delivered') {
      updateData.deliveredAt = new Date();
    }
    // 取消状态处理
    if (status === 'cancelled' && order.canBeCancelled()) {
      updateData.paymentStatus = 'refunded';
    }

    await order.update(updateData);

    res.json({
      success: true,
      message: '订单状态更新成功',
      data: { order }
    });
  } catch (error) {
    next(error);
  }
};